<template>
  <div class="exercise-statistics">
    <div class="page-header">
      <h2>Exercise Statistics</h2>
      <div class="header-actions">
        <el-select v-model="timeFilter" placeholder="Time Period" size="default">
          <el-option label="Last 7 days" value="7days" />
          <el-option label="Last 30 days" value="30days" />
          <el-option label="Last 3 months" value="3months" />
          <el-option label="All time" value="all" />
        </el-select>
        <el-button type="primary" @click="refreshStatistics">
          <el-icon><Refresh /></el-icon>
          Refresh
        </el-button>
      </div>
    </div>

    <div class="statistics-container">
      <el-card v-if="loading" class="loading-card">
        <el-skeleton :rows="5" animated />
      </el-card>

      <div v-else>
        <div class="stats-summary">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-value">{{ stats.totalExercises }}</div>
                <div class="stat-label">Total Exercises</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-value">{{ stats.completedExercises }}</div>
                <div class="stat-label">Completed Exercises</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-value">{{ stats.averageScore }}%</div>
                <div class="stat-label">Average Score</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-value">{{ formatTime(stats.totalTimeSpent) }}</div>
                <div class="stat-label">Total Time Spent</div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <div class="stats-charts">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="chart-card">
                <template #header>
                  <div class="chart-header">
                    <h3>Performance by Category</h3>
                  </div>
                </template>
                <div class="chart-placeholder">
                  <!-- Chart would go here in a real implementation -->
                  <div class="mock-chart">
                    <div v-for="(item, index) in stats.categoryPerformance" :key="index" class="mock-bar-item">
                      <div class="mock-bar-label">{{ item.category }}</div>
                      <div class="mock-bar-container">
                        <div class="mock-bar" :style="{ width: `${item.score}%`, backgroundColor: getScoreColor(item.score) }"></div>
                        <span class="mock-bar-value">{{ item.score }}%</span>
                      </div>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="chart-card">
                <template #header>
                  <div class="chart-header">
                    <h3>Activity Over Time</h3>
                  </div>
                </template>
                <div class="chart-placeholder">
                  <!-- Chart would go here in a real implementation -->
                  <div class="mock-chart">
                    <div v-for="(item, index) in stats.activityOverTime" :key="index" class="mock-line-item">
                      <div class="mock-line-date">{{ formatShortDate(item.date) }}</div>
                      <div class="mock-line-container">
                        <div class="mock-line-bar" :style="{ height: `${item.count * 10}px` }"></div>
                        <span class="mock-line-value">{{ item.count }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <div class="recent-performance">
          <el-card>
            <template #header>
              <div class="card-header">
                <h3>Recent Performance</h3>
              </div>
            </template>
            <el-table :data="stats.recentPerformance" style="width: 100%">
              <el-table-column prop="title" label="Exercise" min-width="200" />
              <el-table-column prop="date" label="Date" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.date) }}
                </template>
              </el-table-column>
              <el-table-column prop="score" label="Score" width="120">
                <template #default="{ row }">
                  <div class="score-display">
                    <el-progress 
                      :percentage="row.score" 
                      :color="getScoreColor(row.score)"
                      :stroke-width="10"
                    />
                    <span>{{ row.score }}%</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="timeSpent" label="Time Spent" width="120">
                <template #default="{ row }">
                  {{ formatTime(row.timeSpent) }}
                </template>
              </el-table-column>
              <el-table-column label="Actions" width="120" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewExercise(row.id)">
                    View
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'ExerciseStatistics',
  components: {
    Refresh
  },
  setup() {
    const router = useRouter()
    const loading = ref(true)
    const timeFilter = ref('7days')
    const stats = ref({
      totalExercises: 0,
      completedExercises: 0,
      averageScore: 0,
      totalTimeSpent: 0,
      categoryPerformance: [],
      activityOverTime: [],
      recentPerformance: []
    })

    const fetchStatistics = async () => {
      loading.value = true
      try {
        // Replace with actual API call
        // const response = await api.getExerciseStatistics({
        //   timePeriod: timeFilter.value
        // })
        // stats.value = response.data

        // Mock data for now
        setTimeout(() => {
          stats.value = {
            totalExercises: 25,
            completedExercises: 18,
            averageScore: 82,
            totalTimeSpent: 28800, // 8 hours in seconds
            categoryPerformance: [
              { category: 'Programming', score: 85 },
              { category: 'Web Development', score: 92 },
              { category: 'Web Design', score: 70 },
              { category: 'Databases', score: 78 },
              { category: 'DevOps', score: 65 }
            ],
            activityOverTime: [
              { date: new Date(Date.now() - 6 * 86400000).toISOString(), count: 2 },
              { date: new Date(Date.now() - 5 * 86400000).toISOString(), count: 1 },
              { date: new Date(Date.now() - 4 * 86400000).toISOString(), count: 3 },
              { date: new Date(Date.now() - 3 * 86400000).toISOString(), count: 0 },
              { date: new Date(Date.now() - 2 * 86400000).toISOString(), count: 2 },
              { date: new Date(Date.now() - 1 * 86400000).toISOString(), count: 4 },
              { date: new Date().toISOString(), count: 1 }
            ],
            recentPerformance: [
              {
                id: 1,
                title: 'JavaScript Basics',
                date: new Date().toISOString(),
                score: 85,
                timeSpent: 1800 // seconds
              },
              {
                id: 2,
                title: 'Vue.js Components',
                date: new Date(Date.now() - 86400000).toISOString(),
                score: 92,
                timeSpent: 2400 // seconds
              },
              {
                id: 3,
                title: 'CSS Flexbox',
                date: new Date(Date.now() - 172800000).toISOString(),
                score: 70,
                timeSpent: 1200 // seconds
              },
              {
                id: 4,
                title: 'SQL Fundamentals',
                date: new Date(Date.now() - 259200000).toISOString(),
                score: 78,
                timeSpent: 3000 // seconds
              },
              {
                id: 5,
                title: 'Docker Basics',
                date: new Date(Date.now() - 432000000).toISOString(),
                score: 65,
                timeSpent: 2700 // seconds
              }
            ]
          }
          loading.value = false
        }, 1000)
      } catch (error) {
        console.error('Error fetching statistics:', error)
        ElMessage.error('Failed to load statistics')
        loading.value = false
      }
    }

    const refreshStatistics = () => {
      fetchStatistics()
    }

    const viewExercise = (id) => {
      router.push(`/dashboard/exercises/${id}`)
    }

    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleString()
    }

    const formatShortDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleDateString()
    }

    const formatTime = (seconds) => {
      if (seconds < 60) {
        return `${seconds}s`
      } else if (seconds < 3600) {
        const minutes = Math.floor(seconds / 60)
        const remainingSeconds = seconds % 60
        return `${minutes}m ${remainingSeconds}s`
      } else {
        const hours = Math.floor(seconds / 3600)
        const minutes = Math.floor((seconds % 3600) / 60)
        return `${hours}h ${minutes}m`
      }
    }

    const getScoreColor = (score) => {
      if (score >= 90) return '#67C23A' // success
      if (score >= 70) return '#E6A23C' // warning
      return '#F56C6C' // danger
    }

    watch(timeFilter, () => {
      fetchStatistics()
    })

    onMounted(() => {
      fetchStatistics()
    })

    return {
      loading,
      timeFilter,
      stats,
      refreshStatistics,
      viewExercise,
      formatDate,
      formatShortDate,
      formatTime,
      getScoreColor
    }
  }
}
</script>

<style scoped>
.exercise-statistics {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.header-actions {
  display: flex;
  gap: 10px;
}

.statistics-container {
  background-color: var(--el-bg-color);
  border-radius: 4px;
  padding: 20px;
}

.loading-card {
  margin-bottom: 20px;
}

.stats-summary {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-color-primary);
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.stats-charts {
  margin-bottom: 20px;
}

.chart-card {
  height: 300px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
}

.chart-placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.mock-chart {
  width: 100%;
  height: 220px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.mock-bar-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.mock-bar-label {
  width: 120px;
  text-align: right;
  padding-right: 10px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.mock-bar-container {
  flex: 1;
  height: 20px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 4px;
  position: relative;
}

.mock-bar {
  height: 100%;
  border-radius: 4px;
}

.mock-bar-value {
  position: absolute;
  right: 8px;
  top: 0;
  line-height: 20px;
  font-size: 12px;
  color: var(--el-color-white);
}

.mock-line-item {
  display: inline-block;
  width: 14%;
  text-align: center;
  height: 220px;
  position: relative;
}

.mock-line-date {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.mock-line-container {
  height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: center;
  padding-bottom: 25px;
}

.mock-line-bar {
  width: 20px;
  background-color: var(--el-color-primary);
  border-radius: 2px 2px 0 0;
}

.mock-line-value {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 5px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
}

.score-display {
  display: flex;
  flex-direction: column;
  gap: 5px;
}
</style> 